package org.example.pmsystem.controller;

import org.example.pmsystem.Response;
import org.example.pmsystem.entity.User;
import org.example.pmsystem.entity.UserRole;
import org.example.pmsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:5173")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public Response<Boolean> login(@RequestBody User user){
        String result = userService.login(user);
        if (result.equals("success"))
            return Response.newSuccess(true);
        return Response.newFail(result);
    }

    @GetMapping("getUserRoleByuserid/{userid}")
    public Response<User> getUserRoleByuserid(@PathVariable String userid){
//        System.out.println(userService.getUserRoleBySno(sno));
        return Response.newSuccess(userService.getUserRoleByuserid(userid));
    }

    @GetMapping("showUsers")
    public Response<List<User>> getAllUser(){
        return Response.newSuccess(userService.getAllUser());
    }

    @PostMapping("createNewUser")
    public Response<Boolean> insertUser(@RequestBody User user) {
        if (userService.insertUser(user))
            return Response.newSuccess(true);
        return Response.newFail("该用户已存在！");
    }

    @PostMapping("insertUserRole")
    public Response<Void> insertUserRole(@RequestBody User user) {
        userService.insertUserRole(user);
        return Response.newSuccess(null);
//        if (userService.insertUserRole(userRole))
//            return Response.newSuccess(true);
//        return Response.newFail("该用户已拥有该角色！");
    }

    @PutMapping("updateUser")
    public Response<Void> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Response.newSuccess(null);
    }

    @DeleteMapping("deleteUserByuserid/{userid}")
    public Response<String> deleteUserByuserid(@PathVariable String userid) {
        userService.deleteUserByuserid(userid);
        return Response.newSuccess("同时删除该用户的所有角色信息、员工信息");
    }

    @DeleteMapping("deleteUserRole")
    public Response<Boolean> deleteUserRole(@RequestBody User user ){
        return Response.newSuccess(userService.deleteUserRole(user));
    }
}
